package school.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import school.domain.News;
import school.domain.User;
import school.mapper.NewsMapper;
import school.service.UserService;
import school.support.BaseController;
import school.support.exception.MessageException;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private NewsMapper newsMapper;

    @RequestMapping("index")
    public String index(Model model){
        List<News> newsList = newsMapper.selectAll();
        model.addAttribute("newsList",newsList);
        return "index";
    }

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @PostMapping("login")
    public String login(String username, String password, HttpSession session){
        User user = userService.login(username, password);
        if(null == user){
            throw new MessageException("用户名或者密码错误");
        }
        session.setAttribute("sessionAdmin",user);
        return "redirect:index.do";
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("sessionAdmin");
        return "redirect:login.do";
    }

}
